package com.rickpan.service.impl;

import com.rickpan.entity.Team;
import com.rickpan.entity.TeamMember;
import com.rickpan.entity.TeamInviteCode;
import com.rickpan.entity.User;
import com.rickpan.repository.TeamRepository;
import com.rickpan.repository.TeamMemberRepository;
import com.rickpan.repository.UserRepository;
import com.rickpan.service.TeamMemberService;
import com.rickpan.service.TeamInviteCodeService;
import com.rickpan.util.ShareCodeGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 团队成员服务实现类
 */
@Service
@Transactional
public class TeamMemberServiceImpl implements TeamMemberService {

    private static final Logger logger = LoggerFactory.getLogger(TeamMemberServiceImpl.class);

    @Autowired
    private TeamMemberRepository teamMemberRepository;

    @Autowired
    private TeamRepository teamRepository;

    @Autowired
    private ShareCodeGenerator shareCodeGenerator;

    @Autowired
    private UserRepository userRepository;

    @Override
    public TeamMember addMember(TeamMember teamMember) {
        logger.info("添加团队成员 teamId={}, userId={}, role={}", 
                   teamMember.getTeamId(), teamMember.getUserId(), teamMember.getRole());
        
        // 检查成员是否已存在
        Optional<TeamMember> existingMember = teamMemberRepository.findByTeamIdAndUserId(
            teamMember.getTeamId(), teamMember.getUserId());
        
        if (existingMember.isPresent()) {
            TeamMember existing = existingMember.get();
            if (existing.getStatus() == TeamMember.Status.ACTIVE) {
                logger.warn("用户已是团队成员 teamId={}, userId={}", 
                           teamMember.getTeamId(), teamMember.getUserId());
                return existing;
            } else {
                // 重新激活成员
                existing.setStatus(TeamMember.Status.ACTIVE);
                existing.setRole(teamMember.getRole());
                TeamMember savedMember = teamMemberRepository.save(existing);
                // 更新团队成员数量
                updateTeamMemberCount(teamMember.getTeamId());
                return savedMember;
            }
        }

        // 保存新成员 - 自动填充用户信息
        fillUserInfo(teamMember);
        TeamMember savedMember = teamMemberRepository.save(teamMember);
        // 更新团队成员数量
        updateTeamMemberCount(teamMember.getTeamId());
        return savedMember;
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<TeamMember> findById(Long id) {
        return teamMemberRepository.findById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<TeamMember> findByTeamIdAndUserId(Long teamId, Long userId) {
        return teamMemberRepository.findByTeamIdAndUserId(teamId, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<TeamMember> findByTeamId(Long teamId) {
        return teamMemberRepository.findByTeamId(teamId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<TeamMember> findByUserId(Long userId) {
        return teamMemberRepository.findByUserId(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<TeamMember> findActiveTeamsByUserId(Long userId) {
        return teamMemberRepository.findActiveTeamsByUserId(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<TeamMember> findByTeamId(Long teamId, Pageable pageable) {
        return teamMemberRepository.findByTeamId(teamId, pageable);
    }

    @Override
    public TeamMember updateMember(TeamMember teamMember) {
        logger.info("更新团队成员 id={}, role={}, status={}", 
                   teamMember.getId(), teamMember.getRole(), teamMember.getStatus());
        
        Optional<TeamMember> existingMember = teamMemberRepository.findById(teamMember.getId());
        if (existingMember.isPresent()) {
            TeamMember existing = existingMember.get();
            existing.setRole(teamMember.getRole());
            existing.setStatus(teamMember.getStatus());
            return teamMemberRepository.save(existing);
        }
        
        throw new RuntimeException("团队成员不存在: " + teamMember.getId());
    }

    @Override
    public void removeMember(Long teamId, Long userId) {
        logger.info("移除团队成员 teamId={}, userId={}", teamId, userId);
        
        Optional<TeamMember> member = teamMemberRepository.findByTeamIdAndUserId(teamId, userId);
        if (member.isPresent()) {
            TeamMember teamMember = member.get();
            
            // 检查是否为团队所有者
            if (teamMember.getRole() == TeamMember.Role.OWNER) {
                throw new RuntimeException("不能移除团队所有者");
            }
            
            // 软删除：设置状态为REMOVED
            teamMember.setStatus(TeamMember.Status.REMOVED);
            teamMemberRepository.save(teamMember);

            // 更新团队成员数量
            updateTeamMemberCount(teamId);
        } else {
            logger.warn("要移除的团队成员不存在 teamId={}, userId={}", teamId, userId);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public boolean isTeamMember(Long teamId, Long userId) {
        return teamMemberRepository.existsByTeamIdAndUserIdAndStatusActive(teamId, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean isTeamAdmin(Long teamId, Long userId) {
        return teamMemberRepository.existsByTeamIdAndUserIdAndRoleAdminOrOwner(teamId, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean isTeamOwner(Long teamId, Long userId) {
        return teamMemberRepository.existsByTeamIdAndUserIdAndRoleOwner(teamId, userId);
    }

    @Override
    @Transactional(readOnly = true)
    public long countByTeamId(Long teamId) {
        return teamMemberRepository.countByTeamId(teamId);
    }

    @Override
    @Transactional(readOnly = true)
    public long countActiveByTeamId(Long teamId) {
        return teamMemberRepository.countActiveByTeamId(teamId);
    }

    /**
     * 获取团队活跃成员列表（按角色排序）
     */
    @Transactional(readOnly = true)
    public List<TeamMember> findActiveByTeamIdOrderByRole(Long teamId) {
        return teamMemberRepository.findActiveByTeamIdOrderByRole(teamId);
    }

    /**
     * 获取用户管理的团队列表
     */
    @Transactional(readOnly = true)
    public List<TeamMember> findManagedTeamsByUserId(Long userId) {
        return teamMemberRepository.findManagedTeamsByUserId(userId);
    }

    /**
     * 批量添加团队成员
     */
    public void addMembers(List<TeamMember> members) {
        logger.info("批量添加团队成员 count={}", members.size());
        
        for (TeamMember member : members) {
            addMember(member);
        }
    }

    /**
     * 更新成员角色
     */
    public TeamMember updateMemberRole(Long teamId, Long userId, TeamMember.Role newRole) {
        logger.info("更新成员角色 teamId={}, userId={}, newRole={}", teamId, userId, newRole);
        
        Optional<TeamMember> member = teamMemberRepository.findByTeamIdAndUserId(teamId, userId);
        if (member.isPresent()) {
            TeamMember teamMember = member.get();
            
            // 检查是否为团队所有者
            if (teamMember.getRole() == TeamMember.Role.OWNER && newRole != TeamMember.Role.OWNER) {
                throw new RuntimeException("不能修改团队所有者的角色");
            }
            
            teamMember.setRole(newRole);
            return teamMemberRepository.save(teamMember);
        }
        
        throw new RuntimeException("团队成员不存在");
    }



    /**
     * 生成团队邀请码
     */
    public String generateInviteCode(Long teamId) {
        logger.info("生成团队邀请码 teamId={}", teamId);

        String inviteCode;
        int attempts = 0;

        // 生成唯一邀请码，最多尝试10次
        do {
            inviteCode = shareCodeGenerator.generateShareCode(8);
            attempts++;
        } while (attempts < 10 && isInviteCodeExists(inviteCode));

        if (attempts >= 10) {
            throw new RuntimeException("生成邀请码失败，请重试");
        }

        logger.info("团队邀请码生成成功 teamId={}, inviteCode={}", teamId, inviteCode);
        return inviteCode;
    }

    /**
     * 通过邀请码加入团队
     */
    public TeamMember joinTeamByInviteCode(String inviteCode, Long userId) {
        logger.info("通过邀请码加入团队 inviteCode={}, userId={}", inviteCode, userId);

        // 这里简化处理，实际应该通过TeamInviteCodeService来验证和处理
        // 暂时返回null，等待TeamInviteCodeService实现后再完善
        logger.warn("邀请码功能暂未完全实现，需要TeamInviteCodeService支持");
        return null;
    }

    /**
     * 检查邀请码是否已存在（简化实现）
     */
    private boolean isInviteCodeExists(String inviteCode) {
        // 这里应该查询TeamInviteCode表，暂时返回false
        return false;
    }

    @Override
    @Transactional
    public TeamMember transferOwnership(Long teamId, Long currentOwnerId, Long newOwnerId) {
        logger.info("转移团队所有权 teamId={}, currentOwnerId={}, newOwnerId={}", teamId, currentOwnerId, newOwnerId);

        // 检查当前所有者
        Optional<TeamMember> currentOwnerOpt = teamMemberRepository.findByTeamIdAndUserId(teamId, currentOwnerId);
        if (!currentOwnerOpt.isPresent() || currentOwnerOpt.get().getRole() != TeamMember.Role.OWNER) {
            throw new RuntimeException("当前用户不是团队所有者");
        }

        // 检查新所有者是否为团队成员
        Optional<TeamMember> newOwnerOpt = teamMemberRepository.findByTeamIdAndUserId(teamId, newOwnerId);
        if (!newOwnerOpt.isPresent() || newOwnerOpt.get().getStatus() != TeamMember.Status.ACTIVE) {
            throw new RuntimeException("新所有者不是团队活跃成员");
        }

        // 不能转移给自己
        if (currentOwnerId.equals(newOwnerId)) {
            throw new RuntimeException("不能转移所有权给自己");
        }

        TeamMember currentOwner = currentOwnerOpt.get();
        TeamMember newOwner = newOwnerOpt.get();

        // 将当前所有者降级为管理员
        currentOwner.setRole(TeamMember.Role.ADMIN);
        teamMemberRepository.save(currentOwner);

        // 将新成员提升为所有者
        newOwner.setRole(TeamMember.Role.OWNER);
        TeamMember savedNewOwner = teamMemberRepository.save(newOwner);

        logger.info("团队所有权转移成功 teamId={}, newOwnerId={}", teamId, newOwnerId);
        return savedNewOwner;
    }

    @Override
    public List<TeamMember> getTeamMembers(Long teamId) {
        return teamMemberRepository.findByTeamIdAndStatus(teamId, TeamMember.Status.ACTIVE);
    }

    @Override
    @Transactional(readOnly = true)
    public boolean canManageTeamSettings(Long teamId, Long userId) {
        // 团队设置可以由OWNER和ADMIN管理
        // 这里使用isTeamAdmin方法，它已经包含了OWNER和ADMIN角色的检查
        return isTeamAdmin(teamId, userId);
    }

    /**
     * 填充用户信息到TeamMember
     */
    private void fillUserInfo(TeamMember teamMember) {
        if (teamMember.getUserId() != null) {
            try {
                Optional<User> userOpt = userRepository.findById(teamMember.getUserId());
                if (userOpt.isPresent()) {
                    User user = userOpt.get();
                    teamMember.setNickname(user.getRealName());
                    teamMember.setUsername(user.getUsername());
                } else {
                    logger.warn("用户不存在: userId={}", teamMember.getUserId());
                }
            } catch (Exception e) {
                logger.error("填充用户信息失败: userId={}", teamMember.getUserId(), e);
            }
        }
    }

    /**
     * 更新团队当前成员数量
     */
    private void updateTeamMemberCount(Long teamId) {
        logger.info("更新团队成员数量 teamId={}", teamId);

        // 统计活跃成员数量
        long activeCount = teamMemberRepository.countByTeamIdAndStatus(teamId, TeamMember.Status.ACTIVE);

        // 更新团队的currentMembers字段
        Optional<Team> teamOpt = teamRepository.findById(teamId);
        if (teamOpt.isPresent()) {
            Team team = teamOpt.get();
            team.setCurrentMembers((int) activeCount);
            teamRepository.save(team);
            logger.info("团队成员数量已更新 teamId={}, currentMembers={}", teamId, activeCount);
        } else {
            logger.warn("团队不存在 teamId={}", teamId);
        }
    }
}
